package com.ccloud.blog.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.ccloud.common.core.model.IpAddressVo;
import com.ccloud.common.core.model.Region;
import com.ccloud.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @version: V1.0
 * @author: chentailai
 * @description: 获取对象的IP地址等信息
 * @className: CusAccessObjectUtil
 * @packageName: com.echo.blog.core.utils
 * @data: 2020/4/28 19:40
 **/
@Component
public class AddressUtil {

    @Resource
    RestTemplate restTemplate;

    private static String APP_KEY = "5526e40f46e350826311902c468b5893";

    /**
     * <从request对象中获取用户IP地址>
     *
     * @param request
     * @return IP地址
     */
    public String getIp(HttpServletRequest request) {
        String forwards = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(forwards) || "unknown".equalsIgnoreCase(forwards)) {
            forwards = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(forwards) || "unknown".equalsIgnoreCase(forwards)) {
            forwards = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(forwards) || "unknown".equalsIgnoreCase(forwards)) {
            forwards = request.getRemoteAddr();
        }
        if (StringUtils.isBlank(forwards) || "unknown".equalsIgnoreCase(forwards)) {
            forwards = request.getHeader("X-Real-IP");
        }
        if (forwards != null && forwards.trim().length() > 0) {
            int index = forwards.indexOf(',');
            return (index != -1) ? forwards.substring(0, index) : forwards;
        }
        return forwards;
    }

    /**
     * @Author chentailai
     * @Description 根据 IP 获取地区
     * @Param [ip]
     * @Return java.lang.String
     * @Date 2020/4/28 19:54
     */
    public String getDistrict(String ip) {
        //新浪查询失败查询阿里
        String result = restTemplate.getForObject("http://apis.juhe.cn/ip/ipNew?ip=" + ip + "&key=" + APP_KEY, String.class, ip);
        IpAddressVo ipAddressVo = JSONObject.parseObject(result, IpAddressVo.class);
        Region region = ipAddressVo.getResult();
        if (region.getIsp().equals("内网IP")) {
            return region.getIsp();
        }
        return region.getCountry() + " | " + region.getCity();

    }

}